package sms

import (
	"math/rand"
	"strconv"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/pkg/errors"
)

func GenerateRandomCode(length int) string {
	source := rand.NewSource(time.Now().UnixNano())
	rng := rand.New(source)

	code := ""
	for i := 0; i < length; i++ {
		code += strconv.Itoa(rng.Intn(10))
	}
	return code
}

type Client interface {
	Send(phoneNumber, code string) error
}

type AliyunClient struct {
	client *dysmsapi.Client
}

func NewAliyunClient(accessKeyId, accessKeySecret string) (*AliyunClient, error) {
	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessKeySecret)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create aliyun client")
	}
	return &AliyunClient{client: client}, nil
}

func (c *AliyunClient) Send(phoneNumber, code string) error {
	request := dysmsapi.CreateSendMessageWithTemplateRequest()
	request.Scheme = "https"

	// 设置请求参数
	request.To = phoneNumber
	request.TemplateCode = "YourTemplateCode" // 替换为你的模板代码
	request.TemplateParam = "{\"code\":\"" + code + "\"}"
	request.SetStringToSign("YourSignName") //签名名称

	_, err := c.client.SendMessageWithTemplate(request)
	if err != nil {
		return errors.Wrap(err, "failed to send sms")
	}
	return nil
}
